package com.formula.propertyshop.utils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.GridView;
import android.widget.ListAdapter;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.model.LatLng;

public class WFUtils {
	/** Create a file Uri for saving an image or video */
	public static Uri getOutputMediaFileUri(int type){
	      return Uri.fromFile(getOutputMediaFile(type));
	}
	/** Create a File for saving an image or video */
	private static File getOutputMediaFile(int type){
	    // To be safe, you should check that the SDCard is mounted
	    // using Environment.getExternalStorageState() before doing this.

	    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
	              Environment.DIRECTORY_PICTURES), "MyCameraApp");
	    // This location works best if you want the created images to be shared
	    // between applications and persist after your app has been uninstalled.

	    // Create the storage directory if it does not exist
	    if (! mediaStorageDir.exists()){
	        if (! mediaStorageDir.mkdirs()){
	            Log.d("MyCameraApp", "failed to create directory");
	            return null;
	        }
	    }

	    // Create a media file name
	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
	    File mediaFile;
	    if (type == Const.MEDIA_TYPE_IMAGE){
	        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
	        "IMG_"+ timeStamp + ".jpg");
	    } else if(type == Const.MEDIA_TYPE_VIDEO) {
	        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
	        "VID_"+ timeStamp + ".mp4");
	    } else {
	        return null;
	    }

	    return mediaFile;
	}
	/**** Method for Setting the Height of the ListView dynamically.
	 **** Hack to fix the issue of not showing all the items of the ListView
	 **** when placed inside a ScrollView  ****/
	public static void setListViewHeightBasedOnChildren(GridView gridView) {
	    ListAdapter listAdapter = gridView.getAdapter();
	    if (listAdapter == null || listAdapter.getCount()==0)
	        return;
	    int itemLines = listAdapter.getCount()/Const.GRIDVIEW_COLUMN_COUNT;
	    int desiredWidth = MeasureSpec.makeMeasureSpec(gridView.getWidth(), MeasureSpec.UNSPECIFIED);
	    int totalHeight = 0;
	    View view = null;
	    for (int i = 0; i < itemLines; i++) {
	        view = listAdapter.getView(i, view, gridView);
	        if (i == 0)
	            view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, LayoutParams.WRAP_CONTENT));

	        view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
	        totalHeight += view.getMeasuredHeight();
	    }
	    ViewGroup.LayoutParams params = gridView.getLayoutParams();
	    params.height = totalHeight + (DeviceInfo.convertDPIToPixel(Const.GRIDVIEW_VERTICAL_SPACE) * itemLines*2);
	    gridView.setLayoutParams(params);
	    gridView.requestLayout();
	}
	public static String getAdressFromLocation(Context context,LatLng currLng)throws Exception{
		String separate = " , ";
		Geocoder geocoder = new Geocoder(context);
		List<Address>addresses = geocoder.getFromLocation(currLng.latitude, currLng.longitude, 1);
		String location = "";
		for(int i=0;i<addresses.get(0).getMaxAddressLineIndex();i++){
			location += addresses.get(0).getAddressLine(i)+separate;
		}
		if(location.contains(separate))
			location = location.substring(0, location.length()-separate.length());
		return location;
	}

	public static LatLng getLocationFromAdress(Context context, String address)
			throws Exception {
		Geocoder geocoder = new Geocoder(context);
		List<Address> addresses = null;	
		addresses = geocoder.getFromLocationName(address, 1);
			
		if (addresses.size() > 0) {
			double latitude = addresses.get(0).getLatitude();
			double longitude = addresses.get(0).getLongitude();
			LatLng currLng = new LatLng(latitude, longitude);
			return currLng;
		}
		return null;
	}
	public static  String getPhoneNumber(Context context){
		TelephonyManager mTelephonyMgr;
	    mTelephonyMgr = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); 
	    String res = mTelephonyMgr.getLine1Number();
	    if(res==null)
	    	res = "";
	    return res;
	}
	public static String getPrimaryEmail(Context context){
		String gmailPatten = "@gmail";
		String possibleEmail = "";
		Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
		try{
			Account[] accounts = AccountManager.get(context).getAccounts();
			if(accounts.length>0)
				possibleEmail = accounts[0].name;
			for (Account account : accounts) {
			    if (emailPattern.matcher(account.name).matches()) {
			        if(account.name.contains(gmailPatten))
			        {
			        	possibleEmail = account.name;
			        	break;
			        }
			   
			    }
			}
		}catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return possibleEmail;
	}
	public static void saveValue(Context context, String key, String value){
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
		Editor editor = settings.edit();
		editor.putString(key, value);
		editor.apply();
	}
	public static void saveIntValue(Context context, String key, int value){
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
		Editor editor = settings.edit();
		editor.putInt(key, value);
		editor.apply();
	}
	public static String getValue(Context context, String key){
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
		return settings.getString(key, "");
	}
	public static int getIntValue(Context context, String key){
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
		return settings.getInt(key, Integer.MIN_VALUE);
	}
	public static String[] removeNull(String[] listImgGalleryUrl){
		
		List<String> list = new ArrayList<String>();
	    for(String s : listImgGalleryUrl) {
	       if(s != null && s.length() > 0) {
	          list.add(s);
	       }
	    }
		return list.toArray(new String[list.size()]);
	}
	public static boolean checkInternetConnection(Context context){
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		  NetworkInfo ni = cm.getActiveNetworkInfo();
		  if (ni == null) {
		   // There are no active networks.
		   return false;
		  } else
		   return true;
	}
	public static boolean checkLocationService(Context context){
		LocationManager lm  = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		boolean gps_enabled = false, network_enabled = false;		
		try {
			gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
		} catch (Exception ex) {
		}
		try {
			network_enabled = lm
					.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		} catch (Exception ex) {
		}

		if (!gps_enabled && !network_enabled) {
			return false;
		}
		return true;
	}
	public static boolean checkGPSisEnable(Context context){
		LocationManager lm  = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		boolean gps_enabled = false;		
		try {
			gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
		} catch (Exception ex) {
		}
		return gps_enabled;
	}
	public static boolean checkPlayServices(Activity context) {
	        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
	        if (resultCode != ConnectionResult.SUCCESS) {
	            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
	                GooglePlayServicesUtil.getErrorDialog(resultCode, context,
	                        Const.PLAY_SERVICES_RESOLUTION_REQUEST).show();
	            } else {
	                Log.e("checkPlayServices", "not supported");
	                context.finish();
	            }
	            GooglePlayServicesUtil.getErrorDialog(resultCode, context,
                        Const.PLAY_SERVICES_RESOLUTION_REQUEST).show();
	            context.finish();
	            return false;    
	        }
	        return true;
	}
	 /**
	     * Gets the current registration ID for application on GCM service, if there is one.
	     * <p>
	     * If result is empty, the app needs to register.
	     *
	     * @return registration ID, or empty string if there is no existing
	     *         registration ID.
	     */
	    public static String getRegistrationId(Context context) {
	        String registrationId = WFUtils.getValue(context, Const.PROPERTY_REG_ID);
	        if (registrationId.isEmpty()) {
	            Log.e("WFUtils getRegistrationId", "Registration not found.");
	            return "";
	        }
	        // Check if app was updated; if so, it must clear the registration ID
	        // since the existing regID is not guaranteed to work with the new
	        // app version.
	        int registeredVersion = WFUtils.getIntValue(context,Const.PROPERTY_APP_VERSION);
	        int currentVersion = getAppVersion(context);
	        if (registeredVersion != currentVersion) {
	            Log.i("WFUtils getRegistrationId", "App version changed.");
	            return "";
	        }
	        return registrationId;
	    }
	    /**
	     * @return Application's version code from the {@code PackageManager}.
	     */
	    public static int getAppVersion(Context context) {
	        try {
	            PackageInfo packageInfo = context.getPackageManager()
	                    .getPackageInfo(context.getPackageName(), 0);
	            return packageInfo.versionCode;
	        } catch (NameNotFoundException e) {
	            // should never happen
	            throw new RuntimeException("Could not get package name: " + e);
	        }
	    }
}
